<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Common
 *
 * @author Administrator
 */
namespace App\Common;

use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use Illuminate\Support\Facades\Redis as Redis;
use Log;
use App\model\ImageManager;

use Tinify;

class Common {
    //put your code here
    static public function validateRequestField( $request = [] , $rule = []  ){
        if( empty( $request ) || empty( $rule)  ){
            return "request或者rule数组不能为空";
        }
        if( count($request) < count($rule) ){
            return '数组个数不匹配';
        }
        
        foreach($rule as $key => $val ){
            if( !$request[ $val ] ) return false;
        }
        return true;
    }
    // 如果数组中没有找到索引值那么就让这个值设为false
    static public function requestIndex($request,$index){
        if( empty($request) || !in_array($request) ) return 'request数组不能为空';
        if( is_string($index) ){
            if( !isset( $quest[ $index ] ) ) $request[ $index ] = false;
            return $request;
        }
        foreach( $request as $v ){
            if( !isset( $quest[ $index ] ) ) $request[ $index ] = false;
        }
        return $request;
    }
//    如果数组中的值存在false的情况下那么就从数组中删除去
    static public function optData( $questData ){
        if( empty($questData) || !in_array($questData) ) return [];
        foreach( $questData as $v ){
            if($v === false) unset( $questData[$v] );
        }
        return $questData;
    }
//    接口成功时调用的函数
    static public function success( $message = null ){
        $responseData = ['successs'=>1];
        
        if( is_string($message) ) $responseData['message']=$message;
        if( is_array($message) ) $responseData['data']=$message;
        
        return json_encode($responseData);
    }
//    接口失败时调用的函数
    static public function error( $errCode = 0, $errMessage="" ){
        throw new \Exception($errMessage,$errCode);
    }
    /**
     * 本地上传图片到七牛
     * @return 返回七牛地址
     */
    static public function uploadPhote(){
        
        $accessKey = env('UPLOAD_PHOTE_KEY');
        $secretKey  = env('UPLOAD_PHOTE_PAS');
        
        // 构建鉴权对象
        $auth = new Auth($accessKey, $secretKey);

        // 要上传的空间
        $bucket = env('QINIU_BUCKET_TEST');

        // 生成上传 Token
        $token = $auth->uploadToken($bucket);

        $tempFile = $_FILES['uploadFile']['tmp_name'];
        
        $fileType = $_FILES['uploadFile']['type'];
        if( strstr( $fileType,'image' ) !== 0 )
            throw new \Exception('只能上传图片类型的');
        $fileInfo = getimagesize( $tempFile );
        $fileSize = [
            'w'=>$fileInfo[0],
            'h'=>$fileInfo[1]
        ];
        // 要上传文件的本地路径
        $filePath = $tempFile;
        $redis = Redis::connection();
        $num = $redis->get('upload_key');
        
        if( $num === null ){
            $num = $redis->set('upload_key',1);
        }else{
            $num = $redis->incr('upload_key');
        }
        
        $prefixPng = '.png';    
        $key = str_pad($num,6,0,STR_PAD_LEFT) . '-' . date('Y-m-d') . $prefixPng;
        // 上传到七牛后保存的文件名

        // 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new UploadManager();
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
//        echo "\n====> putFile result: \n";
        if ($err !== null) {
            Log::info( "图片上传失败{date('Y-m-d')} :" . $err );
            return false;
        } else {
            return env('UPLOAD_QINIU_DIR') . $key;
        }
    }
    /**
     * 上传图片地址到图片表，返回主键
     * 如果上传失败，最多重复3次上传
     * @return int 主键id
     */
    static public function getUploadPhoteFileId( $imgSrc = "" ){
        
        $insertData = [
            'url'=>$imgSrc
        ];
        return ImageManager::insertLastId( $insertData );
        
    }
    /**
     * 将上传图片资源压缩 返回图片在服务器的位置 缩略图 ?imageView2/1/w/200/h/200
     * 保存到传递的一个图片位置 
     * ps: tinypng API: https://tinypng.com/developers/reference/php
     * @param source $formImg 默认为$_FILES
     */
    static public function compressPicture( $formImg = null  ){
        if( empty($formImg) ){
            return false;
        }
		set_time_limit(120);
        $tempSource = $formImg['picture']['tmp_name'];
        $pictureName = $formImg['picture']['name'];
        $tempSourceType = $formImg['picture']['type'];
        $tmpSourceSize = $formImg['picture']['size'];
       

        if( !is_uploaded_file($tempSource) ){
            return false;
        }
        if( !in_array($tempSourceType,['image/gif','image/jpeg','image/pjpeg','image/png','image/x-icon']) ){
            return false;
        }
        
        if( $tmpSourceSize > env('UPLOAD_PICTURE_SIZE') ){
   			return false;
        }
        
        $toImg = env('UPLOAD_FILE') . $pictureName;
        move_uploaded_file($tempSource,$toImg);

		// 如果上传的图片小于配置的大小或者上传的类型不匹配时不进行压缩处理
        if( $tmpSourceSize/1000 <= env('UPLOAD_PICTURE_SMALL_SIZE') || in_array($tempSourceType,['image/x-icon']) ){
			return $toImg;
		}
	
        Tinify\setKey( env('TINYPNG_KEY') );
        $source = Tinify\fromFile($toImg);
        
        $source->toFile($toImg);
	
        return $toImg;
    }
    /**
     * 图片针对一个网络的地址图片进行转移至七牛空间
     * @param String $imgUrl 外链地址 或 服务器实际地址
     */
    static public function uploadUrlPhote( $imgUrl = '' ){
        
        $accessKey = env('UPLOAD_PHOTE_KEY');
        $secretKey  = env('UPLOAD_PHOTE_PAS');
        
        // 构建鉴权对象
        $auth = new Auth($accessKey, $secretKey);

        // 要上传的空间
        $bucket = env('QINIU_BUCKET_MODADA');

        // 生成上传 Token
        $token = $auth->uploadToken($bucket);
        
        $fileInfo = getimagesize( $imgUrl );
        if( $fileInfo === false )
            return false;

        //$tempFile = base64_encode($imgUrl);
        $tempFile = $imgUrl;
        
        $fileType = $fileInfo['mime'];

        if( strpos( $fileType,'image' ) !== 0 )
            throw new \Exception('只能上传图片类型的');
        
        $fileSize = [
            'w'=>$fileInfo[0],
            'h'=>$fileInfo[1]
        ];
        // 要上传文件的本地路径
        $filePath = $tempFile;
        $redis = Redis::connection();
        $num = $redis->get('upload_key');
        
        if( $num === null ){
            $num = $redis->set('upload_key',1);
        }else{
            $num = $redis->incr('upload_key');
        }
        
        $prefixPng = '.png';    
//        $key = str_pad($num,6,0,STR_PAD_LEFT) . '-' . date('Y-m-d') . $prefixPng;
        $pathInfo = pathinfo($filePath);
        $key = $pathInfo['filename']. $prefixPng;
        // 上传到七牛后保存的文件名

        // 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new UploadManager();
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
//        echo "\n====> putFile result: \n";
        if ($err !== null) {
            Log::info( "图片上传失败{date('Y-m-d')} :" . $err );
            return false;
        } else {
            return env('UPLOAD_QINIU_DIR') . $key;
        }
    }
    
}
